<template>
	<view>
		<view class="top-view">
			<u-steps mode="number" :list="numList" :current="0"></u-steps>
		</view>
		<view class="view-bottom-cover">
			<view class="view-file-choosen">
				<u-empty v-if="fileList.length < 1" text="您还没有上传文件哦" mode="list"></u-empty>
				<view v-for="(item,index) in fileList" :key="index" class="view-file-info">
					<u-row :gutter="3">
						<u-col :span="4">
							<view class="view-file-img" v-if="fileIcon[index] === 'doc' || fileIcon[index] ==='docx'">
								<image class="image-file-img" :src="'../../static/images/index/word.png'"></image>
							</view>
							<view class="view-file-img" v-else-if="fileIcon[index] === 'xls' || fileIcon[index] === 'xlsx'">
								<image class="image-file-img" :src="'../../static/images/index/excel.png'"></image>
							</view>
							<view class="view-file-img" v-else-if="fileIcon[index] ==='jpeg' || fileIcon[index] === 'jpg' || fileIcon[index] === 'png'">
								<image class="image-file-img" :src="'../../static/images/index/image.png'"></image>
							</view>
							<view class="view-file-img" v-else-if="fileIcon[index] === 'ppt' || fileIcon[index] === 'pptx' ">
								<image class="image-file-img" :src="'../../static/images/index/ppt.png'"></image>
							</view>
							<view class="view-file-img" v-else>
								<image class="image-file-img" :src="'../../static/images/index/'+fileIcon[index]+'.png'"></image>
							</view>
						</u-col>
						<u-col :span="8">
							<view class="view-file-name">{{item.name}}</view>
							<view class="view-file-upload-time">{{item.time}}</view>
							<view class="view-file-size">{{(item.size/1000000).toFixed(2) +'M'}}</view>
						</u-col>
					</u-row>
				</view>
			</view>
			<view class="view-btn-group">
				<u-button class="btn-btngroup" :ripple="true" type="primary" @click="openPopup">
					<u-icon name="plus" color="white" size="30"></u-icon>上传文件
				</u-button>
			</view>
		</view>
		<u-popup v-model="isOpen_choose" mode="bottom">
			<view class="popup">
				<button type="primary" style="background-color: #1296db; color: #FFFFFF;" @click="choose_file">微信文件</button>
				<button type="primary" style="background-color: #1296db; color: #FFFFFF;" @click="choose_img">本地图片</button>
			</view>
		</u-popup>

	</view>
</template>

<script>
	const time = require("../../utils/net/timechange.js"); //根据自己项目的位置而定
	let count = 0   //用来添加数组，是数组更新的方法不会覆盖

	var app = getApp()

	export default {
		data() {
			return {
				isOpen_choose: false,
	
				token: "",
				count: 0,
			
				fileList: [], //保存选择的文件
				fileIcon: [], //文件后缀
				fileIconList: ["pdf", "doc", "docx", "ppt", "xls", "xlsx", "pptx", "txt", "jpeg", "jpg", "png"], //支持的文件后缀

				numList: [{
					name: '上传文件'
				}, {
					name: '扫码打印'
				}, {
					name: '确认订单'
				}, {
					name: '打印'
				}, ]
			}
		},
		onShow: function() {
			
		},
		onLoad() {
			this.token = uni.getStorageSync('token')
			var that = this
			that.$getPersonFile().then((res)=>{
				for(let i = 0 ;i < res.data.data.length; i++){
					that.$set(that.fileList,i, res.data.data[i])
					that.$set(that.fileList[i],'name', res.data.data[i].fileName)   //添加name属性
					that.$set(that.fileList[i],'time', res.data.data[i].date)   //添加time属性
					this.$set(this.fileList[i], 'checked', false)  	//添加checked属性
					let index = res.data.data[i].type.lastIndexOf('.')   //分割字符串获取。后面的字符
					let icon = res.data.data[i].type.substring(index+1, res.data.data[i].type.length)
					that.$set(that.fileIcon,i,icon)
				}
				that.count = res.data.data.length		
				app.fileList = that.fileList
				app.fileIcon = that.fileIcon
			})
		},
		methods: {
			//上传文件跳出选择框
			openPopup() {
				if (uni.getStorageSync('token')) {
					this.isOpen_choose = true
				}
				else{
					wx.showModal({
						title: '您还未登录，请登录后再使用',
						content: '',
						cancelText: '取消',
						confirmText: '确定',
						success: res => {
							if(res.confirm){
								wx.reLaunch({
									url: '../../pages/entrance/entrance'
								})
							}else{
								uni.showToast({
									title: "请登录后再使用功能",
									icon: "none"
								})
							}
						},
					})
				}
			},

			//判断文件格式是否符合
			isfileIcon(fileIcon, i) {
				return this.fileIconList.indexOf(fileIcon[i])
			},

			//选择本地图片并上传
			choose_img() {
				uni.chooseImage({
					count: 1, //限制只能选择一个文件
					sourceType: ['album'], 	//从相册选择
					success: async(res) => {
						let rightCount = 0 	//用来计算本次选择中正确类型的文件数量
						let errorCount = 0 	//用来计算本次选择中错误类型的文件数量
						this.count = this.fileList.length 	//确保删除文件后数组下标正确性
						for (let i = 0; i < res.tempFiles.length; i++) {
							let count = i + this.count- errorCount 
							this.fileIcon[count] = res.tempFiles[i].path.split('.').pop().toLowerCase() //获取选择文件的后缀并小写化
							if (this.isfileIcon(this.fileIcon, count) != -1) {
								this.$set(this.fileList, count, res.tempFiles[i]) //保存选择的文件信息，uni-app更新数组用$set方法
								this.fileList[count].name = "本地图片" //本地图片没有.name属性所有需要进行赋值
								this.fileList[count].time = time.formatTime(res.tempFiles.time, 'Y/M/D h:m:s') //将获取的时间戳转换
								this.$set(this.fileList[count], 'checked', false) //添加checked属性
								rightCount += 1
								uni.showLoading({
									title: "上传中",
									mask: true
								})
								let fileUuidCount = count 	//数组下标
								let filePath = this.fileList[count].path 	//文件的url
								let token = this.token 	//标识token
								let fileName = this.fileList[count].name   //文件名称
								await this.uploadFile(filePath,fileUuidCount,fileName,token)
							} else {
								this.fileIcon.pop()
								errorCount += 1
								uni.showToast({
									title: "选择的文件类型不支持",
									icon: "none"
								})
							}
						}
						this.count = this.count + rightCount
						app.fileList = this.fileList
						app.fileIcon = this.fileIcon
					}
				})
			},

			//选择微信文件并上传
			choose_file() {
				wx.chooseMessageFile({
					count: 1, //限制只能选择一个文件
					type: 'file', //选择文件类型
					success: async (res) => {
						let rightCount = 0 //用来计算本次选择上传文件中正确类型的文件数量
						let errorCount = 0 //用来计算本次选择上传文件中错误类型的文件数量
						this.count = this.fileList.length
						for (let i = 0; i < res.tempFiles.length; i++) {
							let count = i + this.count- errorCount 
							this.fileIcon[count] = res.tempFiles[i].path.split('.').pop().toLowerCase() //获取选择文件的后缀并小写化
							if (this.isfileIcon(this.fileIcon, count) != -1) { //判断是否是符合标准的文件
								this.$set(this.fileList, count, res.tempFiles[i]) //保存正确类型的文件到fileList数组
								this.fileList[count].time = time.formatTime(res.tempFiles.time, 'Y/M/D h:m:s') //将获取的时间戳转换
								this.$set(this.fileList[count], 'checked', false) //添加checked属性
								rightCount += 1
								uni.showLoading({
									title: "上传中",
									mask: true
								})
								let fileUuidCount = count 	//数组下标
								let filePath = this.fileList[count].path 	//文件的url
								let token = this.token 	//标识token
								let fileName = this.fileList[count].name   //文件名称
								await this.uploadFile(filePath,fileUuidCount,fileName,token,count)
								
							} else {
								this.fileIcon.pop()
								errorCount += 1
								uni.showToast({
									title: "选择的文件类型不支持",
									icon: "none"
								})
							}
						}
						this.count = this.count + rightCount
						app.fileList = this.fileList
						app.fileIcon = this.fileIcon
					}
				})
			},
			
			//上传文件监听
			uploadMonitoring(fileUuid,count) {
				var that = this
				var countMonitoring = 0
				return new Promise((resolve, reject) => {
					const timeout = setInterval(function() {
						that.$uploadFileMonitoring(fileUuid)
							.then(res => {
								// console.log(`${fileUuid}:status ${res.data.data.status}`)
								if (res.data.data.status === 'finish') {
									resolve('finish')
									uni.hideLoading()
									clearInterval(timeout)
									that.isOpen_choose = false   
								}
								if (res.data.data.status === 'waiting') {
									uni.showLoading({
										title: "上传中",
										mask: true
								    })
									countMonitoring++
								}
								
								if(countMonitoring > 60){
									clearInterval(timeout)
								    uni.showToast({
										title: "上传失败，请重新上传",
										icon: "none"
									})
									that.fileList.splice(count, 1)   //删除对应的项
									that.fileIcon.splice(count, 1)   //删除对应的图标
									that.isOpen_choose = false   
								}
								
							})
							
					}, 1000)
					
				})
			},

			//上传文件
			uploadFile(filePath, fileUuidCount,fileName,token,count) {
				this.$myUploadFile.uploadFile(filePath,fileName,token).then(
					async res => {
							var that = this
							let resData = JSON.parse(res.data) //将获取的信息装换成json格式读取，否则读取到的会为空
							let fileUuid = resData.fileUuid
							that.$set(that.fileList[fileUuidCount], 'fileUuid', fileUuid) //添加fileUuid属性
							// console.log("fileUuid:", fileUuid)
							await that.uploadMonitoring(fileUuid,count)
					},
					err => {
						
					}
				)
			}
				
		},

	}
</script>

<style>
	.top-view {
		margin-top: 40rpx;
	}

	.view-bottom-cover {
		background-color: #f3f4f6;
		margin-top: 40rpx;
		height: calc(100vh - 170rpx);
		padding: 20rpx 30rpx;

	}

	.view-file-choosen {
		padding: 20rpx;
		width: 100%;
		height: calc(100% - 200rpx);
		background-color: white;
		overflow-y: auto;
		overflow-x: hidden;
	}

	.view-file-info {
		border: 1rpx solid #F1F1F1;
		width: 100%;
		height: 200rpx;
	}

	.view-btn-group {
		margin-top: 15rpx;
		width: 100%;
		height: 190rpx;
	}

	.btn-btngroup {
		margin-top: 15rpx;
		margin-bottom: 15rpx;
		display: block;
	}

	.view-file-img {
		/* background-color: red; */
		margin: 30rpx 30rpx;
		width: 130rpx;
		height: 130rpx;
	}

	.view-file-name {
		/* background-color: red; */
		margin-top: 15rpx;
		margin-bottom: 15rpx;
		width: calc(100% - 10rpx);
		height: 60rpx;
		line-height: 60rpx;
		font-size: 28rpx;
		font-weight: bolder;
	}

	.view-file-upload-time {
		/* background-color: red; */
		margin-top: 15rpx;
		margin-bottom: 15rpx;
		width: calc(100% - 10rpx);
		height: 30rpx;
		line-height: 30rpx;
		font-size: 20rpx;
		color: #C9C9C9;
		text-align: right;
	}

	.view-file-size {
		/* background-color: red; */
		margin-top: 30rpx;
		margin-bottom: 15rpx;
		width: calc(100% - 10rpx);
		height: 30rpx;
		line-height: 30rpx;
		font-size: 20rpx;
		color: #C9C9C9;
		text-align: right;
	}

	.image-file-img {
		width: 100%;
		height: 100%;
	}

	.popup {
		height: 300rpx;
		background-color: #FFFFFF;
		display: flex;
		flex-wrap: wrap;
		text-align: center;
		align-items: center;

	}
</style>
